/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.model.handler;

import java.lang.reflect.Method;
import java.util.Collection;

import javassist.util.proxy.MethodHandler;

import com.koylu.caffein.query.Query;

public class OneToManyContainerHandler implements MethodHandler {

	private Class<? extends Collection<?>> returnType;
	private Query query;
	private Collection<?> lazyLoadedCollection;
	private Integer size;

	public OneToManyContainerHandler(Class<? extends Collection<?>> returnType, Query query) {
		this.returnType = returnType;
		this.query = query;
	}
	
	public Object invoke(Object object, Method method, Method proceed, Object[] args) throws Throwable {
		String methodName = method.getName();
		if ("getQuery".equals(methodName)) {
			return query;
		} else if ("size".equals(methodName)) {
			if (lazyLoadedCollection == null) {
				if (size == null) {
					size = query.count();
				}
				return size;
			}
			return lazyLoadedCollection.size();
		}
		if (lazyLoadedCollection == null) {
			lazyLoadedCollection = query.collection(returnType);
		}
		return method.invoke(lazyLoadedCollection, args);
	}
}